﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using MinistryManager.DataAccess.Entities;
using MinistryManager.DataAccess.Services.ServiceInterfaces;
using MinistryManager.Util.Authentication;
using MinistryManager.Util.Helpers;
using Moq;


namespace MinistryManager.Tests.Login
{
    [TestClass]
    public class LoginHelperTests
    {
        [TestMethod]
        public void VerifyFormsAuthenticationSetAuthCookiesIsCalled()
        {
            const string username = "rubencg";
            const string password = "123";

            var authForms = new Mock<IFormsAuthentication>();
            var volunteerService = GetValidUserMockUserService(username);
            var loginHelper = new LoginHelper(authForms.Object, volunteerService.Object);

            loginHelper.LoginUser(username, password);

            authForms.Verify(a => a.SetAuthenticationUser(username), Times.Once);
        }

        [TestMethod]
        public void LoginOnlyIfIsAValidUser()
        {
            const string username = "rubencg";
            const string correctPassword = "correctPassword";
            const string invalidPassword = "invalidPassword";

            var authForms = new Mock<IFormsAuthentication>();
            var volunteerService = new Mock<IVolunteerService>();
            volunteerService.Setup(us => us.GetUserByUserNameAndPassword(username, correctPassword)).Returns(new Volunteer(){Username = username});
            var loginHelper = new LoginHelper(authForms.Object, volunteerService.Object);

            loginHelper.LoginUser(username, invalidPassword);
            volunteerService.Verify(a => a.GetUserByUserNameAndPassword(username, correctPassword), Times.Never);
            authForms.Verify(a => a.SetAuthenticationUser(username), Times.Never);

            loginHelper.LoginUser(username, correctPassword);
            volunteerService.Verify(a => a.GetUserByUserNameAndPassword(username, correctPassword), Times.Once);
            authForms.Verify(a => a.SetAuthenticationUser(username), Times.Once);
        }

        private Mock<IVolunteerService> GetValidUserMockUserService(string username)
        {
            var volunteerService = new Mock<IVolunteerService>();
            volunteerService.Setup(us => us.GetUserByUserNameAndPassword(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(new Volunteer() { Username = username });
            return volunteerService;
        }
    }
}
